<template>
    <div class="clock">
        {{ currentTime }}
    </div>
</template>

<script>
    export default {
        name: 'Clock',
        data() {
            return {
                currentTime: ''
            };
        },
        created() {
            this.updateTime();
            this.interval = setInterval(this.updateTime, 1000);
        },
        beforeUnmount() {
            clearInterval(this.interval);
        },
        methods: {
            updateTime() {
                this.currentTime = this.formatDate(new Date());
            },
            // 获取右上角的时间戳
            formatDate(date) {
                let newTime = "";
                let year = date.getFullYear(),
                    month = date.getMonth() + 1,//月份是从0开始
                    day = date.getDate(),
                    hour = date.getHours(),
                    min = date.getMinutes(),
                    sec = date.getSeconds();
                if (hour < 10) {
                    hour = "0" + hour;
                }
                if (min < 10) {
                    min = "0" + min;
                }
                if (sec < 10) {
                    sec = "0" + sec;
                }
                newTime = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
                return newTime;
            }
        }
    };
</script>

<style scoped>
    .clock {
        font-size: 2em;
        text-align: center;
        margin-top: 20px;
    }
</style>
